<template>
	<view class="page-cont" :style="useTheme.theme">
		<navbar title="告警详情"></navbar>
		<view class="main-cont" :style="{height: pageHeight}">
			<!-- 预警信息 -->
			<view class="warn-info">
				<view class="warn-info-device">
					<view class="warn-info-device-name">{{warnData.title}}</view>
					<view class="warn-info-device-status">待处理</view>
				</view>
				<view class="warn-info-project">{{warnData.warningPmName}}</view>
				<view class="warn-info-title">预警信息</view>
				<view class="warn-info-form">
					<view class="warn-info-form-item">
						<view class="warn-info-form-label">报警等级</view>
						<view class="warn-info-form-value">{{warnLevel[warnData.level]}}</view>
					</view>
					<view class="warn-info-form-item">
						<view class="warn-info-form-label">报警类型</view>
						<view class="warn-info-form-value">{{warnType[warnData.wartype]}}</view>
					</view>
					<view class="warn-info-form-item">
						<view class="warn-info-form-label">当前状态</view>
						<view class="warn-info-form-value">{{warnData.status == 1 ? '告警中' : '结束'}}</view>
					</view>
					<view class="warn-info-form-item" v-if="warnData.notis">
						<view class="warn-info-form-label">报警规则</view>
						<view class="warn-info-form-value">{{warnData.notis}}</view>
					</view>
					<view class="warn-info-form-item">
						<view class="warn-info-form-label">持续时长</view>
						<view class="warn-info-form-value">{{warnData.diff}}</view>
					</view>
					<view class="warn-info-form-item" v-if="warnData.status!=1">
						<view class="warn-info-form-label">确认人</view>
						<view class="warn-info-form-value"></view>
					</view>
					<view class="warn-info-form-item" v-if="warnData.status!=1">
						<view class="warn-info-form-label">确认时间</view>
						<view class="warn-info-form-value"></view>
					</view>
					<view class="warn-info-form-item">
						<view class="warn-info-form-label">原因及处理方式</view>
						<view class="warn-info-form-value">{{warnData.analysismsg}}</view>
					</view>
					<view class="warn-info-form-item">
						<view class="warn-info-form-label">报警通知人数</view>
						<view class="warn-info-form-value warn-message">
							<view>{{warnData.notices}}</view>
							<view class="warn-message-btn" @click="handleDetail">查看详情</view>
						</view>
					</view>
				</view>
			</view>
			<!-- 历史数据 -->
			<view class="warn-history">
				<view class="warn-history-header">
					<view class="warn-history-title">历史数据</view>
					<image class="warn-history-fullscreen" src="/static/fullscreen.png" @tap="toCharDetail"></image>
				</view>
				<view class="warn-history-time">
					<view :class="[timeActive == index ? 'warn-history-time-active' : 'warn-history-time-item']"
						v-for="(item, index) in timeList" :key="index" @click="dataTimeChange(index)">
						{{item.name}}
					</view>
				</view>
				<DetailChart class="warn-history-chart" :chartData="chartData"></DetailChart>
			</view>
			<!-- 告警确认 -->
			<view v-if="warnData.refid" class="warn-btn">
				<view class="warn-btn-edit" @click="handleSetting">修改阈值</view>
				<view class="warn-btn-confirm" @click="handleConfirm">告警确认</view>
			</view>
			<view v-else class="warn-confirm" @click="handleConfirm">告警确认</view>
		</view>
		<!-- 弹框：告警确认 -->
		<uni-popup ref="popup" type="bottom" background-color="#fff">
			<view class="popup-cont">
				<view class="popup-title">预警确认</view>
				<view class="popup-handle">
					<!-- 告警中：可以延时提醒 -->
					<view v-if="warnData.status == 1" class="popup-handle-title">延时提醒</view>
					<view v-if="warnData.status == 1" class="popup-handle-delay">
						<view :class="[delayActive == index ? 'popup-handle-active' : 'popup-handle-time']"
							v-for="(item, index) in delayList" :key="index" @click="delayActive = index">{{item.name}}
						</view>
					</view>
					<view class="popup-handle-title">原因及处理方式</view>
					<view class="popup-handle-option">
						<uni-easyinput v-model="formData.comments" type="textarea" placeholder="请输入原因及处理方式"
							:clearable="false" />
					</view>
				</view>
				<view class="popup-btn">
					<view class="popup-btn-cancel" @click="handleCancel(1)">取消</view>
					<view class="popup-btn-confirm" @click="handleConfirmData(1)">确认</view>
				</view>
			</view>
		</uni-popup>
		<!-- 弹框：告警二次确认 -->
		<uni-popup ref="popupTip" type="center" background-color="#fff">
			<view class="popup-cont popup-tip">
				<view class="popup-title">提示</view>
				<view class="popup-detail">报警清除后不可恢复，是否确认？</view>
				<view class="popup-btn">
					<view class="popup-btn-close" @click="handleCancel(2)">取消</view>
					<view class="popup-btn-submit" @click="handleConfirmData(2)">确认</view>
				</view>
			</view>
		</uni-popup>
		<!-- 设置阈值 -->
		<uni-popup ref="inputDialog" type="center">
			<view class="popup-cont popup-tip">
				<view class="popup-title">修改阈值</view>
				<view class="popup-form">
					<uni-forms ref="updateForm" :value="formData" :rules="rules" labelPosition="top" labelWidth="200">
						<uni-forms-item label="阈值" name="v" required>
							<uni-easyinput v-model="formData.v" placeholder="请输入" :clearable="false" />
						</uni-forms-item>
						<uni-forms-item label="延迟时间(秒)" name="delayed" required>
							<uni-easyinput v-model="formData.delayed" placeholder="请输入" :clearable="false" />
						</uni-forms-item>
						<uni-forms-item label="推送周期(分钟)" name="cycle" required>
							<uni-easyinput v-model="formData.cycle" placeholder="请输入" :clearable="false" />
						</uni-forms-item>
					</uni-forms>
				</view>
				<view class="popup-btn">
					<view class="popup-btn-close" @click="handleCancel(3)">取消</view>
					<view class="popup-btn-submit" @click="handleConfirmData(3)">确认</view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>
<script setup lang="ts">
	import { defineComponent, reactive, ref, watch, getCurrentInstance } from 'vue';
	import { onShow, onLoad, onUnload } from "@dcloudio/uni-app";
	import { storeToRefs } from 'pinia';
	import { useNavbar, useDict } from "@/utils/hooks.js"
	import { getWarnDetail, confirmWarn, updateWarnTop } from "@/api/warn.js";
	import DetailChart from "./components/detail-chart.vue";
	import useThemeStore from '@/store/theme';
	import useHomeStore from '@/store/home';
	import { getDataHistory } from "@/api/home.js";
	const { proxy } = getCurrentInstance();
	const { pageHeight } = useNavbar();
	const { warnLevel, warnType } = useDict();
	const useTheme = useThemeStore();
	const homeStore = useHomeStore();
	const { projectId, projectName, warnId, deviceId, deviceList } = storeToRefs(homeStore);
	const datamapping = ref("")
	const chartData = ref([])
	const inputDialog = ref()
	const warnData = ref({
		analysisid: '',
		analysismsg: '',
		confirm: '',
		id: '',
		level: '',
		mid: '',
		notices: "",
		notifyidx: '',
		oid: '',
		show: '',
		starttime: '',
		status: '',//0：告警中，1：结束
		title: '',
		type: '',
		unit: "",
		warningPmName: '',
		wartype: '',
		endtime: '',
		warnigmsg: '',
		refid: '',
		notis: '',//报警规则
		diff: '',//持续时长
	})

	const timeList = ref([{ name: '报警期间', value: 0 }, { name: '近1天', value: 1 }, { name: '近3天', value: 2 }, { name: '近1周', value: 3 }])
	const timeActive = ref(0)
	const delayList = ref([
		{ name: '30分钟', value: 30 },
		{ name: '1小时', value: 60 },
		{ name: '3小时', value: 180 },
		{ name: '6小时', value: 360 },
		{ name: '12小时', value: 720 },
		{ name: '24小时', value: 1440 },
		{ name: '不再提示', value: 0 },
	])
	const delayActive = ref(0)
	const popup = ref()
	const popupTip = ref()
	const updateForm = ref()
	const customAlarm = ref()
	const formData = reactive({
		delayed: 0,//延时提醒，单位分钟
		comments: "",//原因及处理方式
		v: "",//阈值
		cycle: "",//推送周期
		notices: [],//通知组
	})
	const rules = reactive({
		delayed: {
			rules: [{
				required: true,
				errorMessage: "延迟时间不能为空",
			},],
		},
		cycle: {
			rules: [{
				required: true,
				errorMessage: "推送周期不能为空",
			},],
		},
	})

	// 监听时间筛选
	watch(() => timeActive, () => {

	});

	onLoad(() => {

		getDetail();
	});

	onUnload(() => {
		// homeStore.clearProjectData();
	});

	function getDetail() {
		if (!warnId.value) {
			return;
		}
		getWarnDetail({ id: warnId.value, status: 1 }).then(res => {
			warnData.value = res.data;
			warnData.value.warningPmName = projectName.value;
			datamapping.value = `${warnData.value.type}_0_${warnData.value.oid}_0`;
			if (warnData.value.endtime) {
				let second = proxy.dayjs(warnData.value.endtime).diff(warnData.value.starttime);
				warnData.value.diff = convertSeconds(Number(second));

				getCharData(warnData.value.starttime, warnData.value.endtime);
			} else {
				//未结束 持续到当前
				let second = proxy.dayjs().diff(warnData.value.starttime);
				warnData.value.diff = convertSeconds(Number(second));

				getCharData(warnData.value.starttime, proxy.dayjs().format("YYYY-MM-DD HH:mm:ss"));
			}

			if (res.customAlarm) {
				customAlarm.value = res.customAlarm;
				formData.v = res.customAlarm.v;//阈值
				let notis = JSON.parse(res.customAlarm.notis || "");
				let obj = notis && notis.length ? notis[0] : "";
				warnData.value.notis = `延迟时间${obj.delayed || '-'}秒，推送周期${obj.cycle || '-'}分钟`;//报警规则

				formData.delayed = obj.delayed;
				formData.cycle = obj.cycle;
				formData.notices = obj.notices || [];
			}
		});


	}

	const charParams = ref({ keys: [], startTime: String, endTime: String })
	function getCharData(startTime, endTime) {
		charParams.value = {
			keys: [datamapping.value],
			startTime: startTime,
			endTime: endTime
		};
		getDataHistory(charParams.value).then(res => {
			chartData.value = [];
			let arr = res[datamapping.value];
			if (arr && arr.length) {
				arr.forEach(element => {
					if (element && element.length) {
						chartData.value.push({
							time: proxy.dayjs(element[0]).format("YYYY-MM-DD HH:mm:ss"),
							num: element[1],
						});
					}
				});
			}
		});
	}


	function dataTimeChange(index) {
		timeActive.value = index
		switch (index) {
			case 0:
				if (warnData.value.endtime) {
					getCharData(warnData.value.starttime, warnData.value.endtime);
				} else {
					getCharData(warnData.value.starttime, proxy.dayjs().format("YYYY-MM-DD HH:mm:ss"));
				}
				break
			case 1:
				getCharData(proxy.dayjs().subtract(1, 'day').format('YYYY-MM-DD HH:mm:ss'), proxy.dayjs().format("YYYY-MM-DD HH:mm:ss"))
				break
			case 2:
				getCharData(proxy.dayjs().subtract(3, 'day').format('YYYY-MM-DD HH:mm:ss'), proxy.dayjs().format("YYYY-MM-DD HH:mm:ss"))
				break
			case 3:
				getCharData(proxy.dayjs().subtract(7, 'day').format('YYYY-MM-DD HH:mm:ss'), proxy.dayjs().format("YYYY-MM-DD HH:mm:ss"))
				break
		}
	}

	// 报警通知详情
	function handleDetail() {
		uni.navigateTo({
			url: '/pages/warn/record'
		});
	}

	// 告警确认
	function handleConfirm() {
		popup.value.open();
	}

	// 告警取消
	function handleCancel(e) {
		if (e == 1) {
			popup.value.close();
		} else if (e == 2) {
			popupTip.value.close();
		} else if (e == 3) {
			inputDialog.value.close();
		}
	}

	// 修改阈值
	function handleSetting() {
		inputDialog.value.open();
	}

	// 告警配置
	function handleConfirmData(e) {
		if (e == 1) {
			if (!formData.comments) {
				uni.showToast({
					title: '请输入原因及处理方式',
					icon: 'none'
				});
				return;
			}
			popupTip.value.open();
		} else if (e == 2) {
			// 告警二次确认
			popup.value.close();
			popupTip.value.close();
			formData.delayed = delayList.value[delayActive.value].value;
			let params = {
				id: warnId.value,//告警id
				mid: projectId.value,//项目Id
				name: warnData.value.title,
				type: 0,//0 确认告警 1：隐藏告警
				status: warnData.value.status,//
				delayed: formData.delayed, //延迟时间
				comments: formData.comments,//解决方式
			}
			if (formData.delayed == 0) {
				// 隐藏告警
				params.type = 1;//隐藏告警
			}
			confirmWarn(params).then(res => {
				uni.showToast({
					title: '告警确认成功',
					icon: 'none'
				});
				uni.$emit("updateWarn");
				setTimeout(() => {
					uni.navigateBack({
						delta: -1
					});
				}, 500)
			});
		} else if (e == 3) {
			// 修改阈值
			updateForm.value.validate().then((valid = false) => {
				if (valid) {
					let params = JSON.parse(JSON.stringify(customAlarm.value));
					params.mid = projectId.value;//项目Id
					params.notis = JSON.stringify([{ delayed: formData.delayed, cycle: formData.cycle, notices: formData.notices }]);//
					updateWarnTop(params).then(res => {
						uni.showToast({
							title: '修改成功',
							icon: 'none'
						});
						uni.$emit("updateWarn");
						setTimeout(() => {
							uni.navigateBack({
								delta: -1
							});
						}, 500)
					});
				}
			});

		}
	}

	// 全屏
	function toCharDetail() {
		uni.navigateTo({
			url: `/pages/warn/detail-landscape?keys=${charParams.value.keys[0]}&startTime=${charParams.value.startTime}&endTime=${charParams.value.endTime}`
		});
	}

	// 时间戳转换
	function convertSeconds(seconds : number) {
		seconds = seconds / 1000;
		const days = Math.floor(seconds / (24 * 3600));
		const hours = Math.floor((seconds % (24 * 3600)) / 3600);
		const minutes = Math.floor((seconds % 3600) / 60);
		const secs = Math.floor(seconds % 60);
		let str = "";
		if (days) {
			str += `${days}天`;
		}
		if (hours) {
			str += `${hours}小时`;
		}
		if (minutes) {
			str += `${minutes}分`;
		}
		str += `${secs}秒`;
		return str;
	}
</script>
<style lang="scss" scoped>
	.page-cont {
		position: relative;

		.main-cont {
			padding: 10px;
			padding-bottom: 80px;
		}

		.warn-info,
		.warn-history {
			padding: 20rpx;
			border-radius: 10rpx;
			background-color: #fff;
		}

		.warn-history {
			margin-top: 30rpx;
			margin-bottom: 80rpx;
		}

		.warn-info-device {
			display: flex;

			.warn-info-device-name {
				width: calc(100% - 124rpx);
				color: #333;
				font-size: 28rpx;
				font-weight: 600;
				word-break: break-all;
			}

			.warn-info-device-status {
				margin-left: 20rpx;
				width: 104rpx;
				height: 36rpx;
				line-height: 36rpx;
				color: #F9AD5F;
				font-size: 23rpx;
				text-align: center;
				border-radius: 18rpx;
				border: 1px solid #F9AD5F;
				background-color: rgba(249, 173, 95, 0.2);

				&.status-blue {
					color: $theme-color;
					border-color: $theme-color;
					background-color: rgba(95, 131, 249, 0.2);
				}

				&.status-yellow {
					color: #F9AD5F;
					border-color: #F9AD5F;
					background-color: rgba(249, 173, 95, 0.2);
				}
			}
		}

		.warn-info-project {
			margin-top: 20rpx;
			padding: 12rpx 20rpx;
			color: #6E84A2;
			border-radius: 5rpx;
			background-color: #F2F4FB;
		}

		.warn-info-title {
			margin-top: 50rpx;
			color: #333;
			font-size: 25rpx;
			font-weight: 600;
		}

		.warn-info-form {
			margin-top: 20rpx;

			.warn-info-form-item {
				padding: 10px;
				display: flex;
				justify-content: space-between;
				border-bottom: 2rpx solid #ccc;
				background-color: #F2F3F9;

				&:first-child {
					border-top-left-radius: 5rpx;
					border-top-right-radius: 5rpx;
				}

				&:nth-child(8) {
					border: none;
					border-bottom-left-radius: 5rpx;
					border-bottom-right-radius: 5rpx;
				}

				&:last-child {
					margin-top: 20rpx;
					border: none;
					border-radius: 10rpx;
					overflow: hidden;
				}
			}

			.warn-info-form-label,
			.warn-info-form-value {
				width: 100px;
				color: #999;
				font-size: 25rpx;
			}

			.warn-info-form-value {
				width: calc(100% - 100px);
				color: #333;
				font-weight: 600;
				word-break: break-all;
			}
		}

		.warn-message {
			display: flex;
			align-items: center;

			.warn-message-btn {
				padding-left: 30rpx;
				color: #2C5AEE;
				font-size: 23rpx;
			}
		}

		.warn-history-header {
			display: flex;
			justify-content: space-between;
			align-items: center;

			.warn-history-title {
				color: #333;
				font-size: 28rpx;
				font-weight: 600;
			}

			.warn-history-fullscreen {
				width: 30rpx;
				height: 30rpx;
			}
		}

		.warn-history-time {
			margin-top: 30rpx;
			display: flex;

			.warn-history-time-item,
			.warn-history-time-active {
				margin-left: 30rpx;
				height: 60rpx;
				line-height: 60rpx;
				flex: 1;
				color: #5A6570;
				font-size: 22rpx;
				text-align: center;
				border-radius: 5rpx;
				border: 1px solid #ccc;
				background-color: #fff;

				&:first-child {
					margin-left: 0;
				}
			}

			.warn-history-time-active {
				color: $theme-color;
				border-color: $theme-color;
				background-color: rgba(95, 131, 249, 0.1);
			}
		}

		.warn-history-chart {
			position: relative;
			margin-top: 40rpx;
			height: 400rpx;
		}

		.warn-confirm {
			position: fixed;
			left: 0;
			bottom: 0;
			width: 100%;
			height: 50px;
			line-height: 50px;
			color: #fff;
			font-size: 14px;
			text-align: center;
			background-color: $theme-color;
		}

		.warn-btn {
			position: fixed;
			left: 0;
			bottom: 0;
			width: 100%;
			display: flex;
			box-sizing: border-box;

			.warn-btn-edit,
			.warn-btn-confirm {
				width: 50%;
				height: 50px;
				line-height: 50px;
				color: #fff;
				font-size: 28rpx;
				text-align: center;
				background-color: #F4B140;
			}

			.warn-btn-confirm {
				background-color: $theme-color;
			}
		}
	}

	.popup-cont {
		background: #fff;

		&.popup-tip {
			width: 80vw;
			border-radius: 10rpx;
			overflow: hidden;
		}

		.popup-title {
			height: 100rpx;
			line-height: 100rpx;
			color: #333;
			font-size: 28rpx;
			font-weight: 600;
			text-align: center;
			border-bottom: 2rpx solid #ccc;
		}

		.popup-handle {
			margin-bottom: 90rpx;
			padding: 50rpx;
			box-sizing: border-box;
		}

		.popup-handle-title {
			margin-bottom: 34rpx;
			color: #333;
			font-size: 25rpx;
			font-weight: 600;
		}

		.popup-handle-delay {
			margin-bottom: 60rpx;
			display: flex;
			flex-wrap: wrap;

			.popup-handle-time,
			.popup-handle-active {
				margin-left: 30rpx;
				width: calc(25% - 25rpx);
				height: 70rpx;
				line-height: 70rpx;
				color: #5A6570;
				font-size: 22rpx;
				text-align: center;
				border-radius: 5rpx;
				background-color: #fff;
				border: 2rpx solid #ccc;
				box-sizing: border-box;

				&:nth-child(4n + 1) {
					margin-left: 0;
				}

				&:nth-child(n + 5) {
					margin-top: 30rpx;
				}
			}

			.popup-handle-active {
				color: $theme-color;
				border-color: $theme-color;
				background-color: rgba(95, 131, 249, 0.1);
			}
		}

		.popup-detail {
			padding: 25px;
			color: #333;
			font-size: 14px;
			font-weight: 600;
			text-align: center;
		}

		.popup-form {
			padding: 10px;

			::v-deep .uni-easyinput__content {
				border-radius: 0;
			}
		}

		.popup-btn {
			padding: 30rpx;
			display: flex;
			align-items: center;
			box-sizing: border-box;

			.popup-btn-cancel,
			.popup-btn-confirm {
				width: 33.3%;
				height: 90rpx;
				line-height: 90rpx;
				color: #333;
				font-size: 28rpx;
				font-weight: 600;
				text-align: center;
				background-color: #fff;
			}

			.popup-btn-confirm {
				width: 66.6%;
				color: #fff;
				border-radius: 5rpx;
				background-color: $theme-color;
			}

			.popup-btn-close,
			.popup-btn-submit {
				width: calc(50% - 20rpx);
				height: 90rpx;
				line-height: 90rpx;
				color: #333;
				font-size: 28rpx;
				font-weight: 600;
				text-align: center;
				border-radius: 5rpx;
				background-color: #F2F4FB;
			}

			.popup-btn-submit {
				margin-left: 40rpx;
				color: #fff;
				background-color: $theme-color;
			}
		}
	}
</style>